package com.tpu.daoclasses;

import org.apache.hivemind.Discardable;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class DefaultSessionOwner implements SessionOwner, Discardable{
	private SessionCreator creator;
	private Session session;
	private Transaction tx;
	private boolean isToRollback;
	public Session getSession() {
	if (session == null) {
	session = creator.createSession();
	if (tx == null) {
	tx = session.beginTransaction();
	isToRollback = false;
	  }
	}
	return session;
	}
	public void threadDidDiscardService() {
	if (session != null) {
	try {
	endTransaction();
	} finally {
	session.close();
	session = null;
	    }
	  }
	}
	public void setToRollback() {
	isToRollback = true;
	   }
	public void endTransaction() {
	if (tx != null) {
	try {
	if (isToRollback) {
	tx.rollback();
	} else {
	tx.commit();
	  }
	} catch (RuntimeException e) {
	tx.rollback();
	throw e;
	} finally {
	tx = null;
	      }
	    }
	  }
	}
